import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl

# 设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 正确显示负号

# 尝试设置兼容的后端
try:
    mpl.use('TkAgg')  # 尝试使用 TkAgg 后端
except:
    pass  # 如果失败，继续使用默认后端

# Load the uploaded CSV file to inspect its contents
file_path = 'job.csv'
job_data = pd.read_csv(file_path)
# Display the first few rows of the dataset to understand its structure
job_data.head()

# Step 1: Process the salary column to extract the minimum salary and convert it to "元"
def process_salary(salary):
    try:
        # Remove "K" and split by '-' to get the lower bound of the salary
        min_salary = salary.split('-')[0].replace('K', '').strip()
        return int(min_salary) * 1000  # Convert "K" to "元"
    except:
        return None  # Handle potential errors gracefully

# Apply the function to preprocess the "薪资" column
job_data['最低薪资'] = job_data['薪资'].apply(process_salary)
filtered_data = job_data.dropna(subset=['最低薪资'])
# Step 2: Count the number of job positions for each salary level
salary_counts = filtered_data['最低薪资'].value_counts().sort_index()

# Plot a bar chart for salary levels
plt.figure(figsize=(12, 8))
plt.bar(salary_counts.index, salary_counts.values, width=500, color='skyblue', edgecolor='black')
plt.title('不同薪资水平的岗位数量', fontsize=16)
plt.xlabel('最低薪资 (元)', fontsize=12)
plt.ylabel('岗位数量', fontsize=12)
# Use formatted labels for the x-axis
plt.xticks(salary_counts.index, [f"{int(x)} 元" for x in salary_counts.index], rotation=45, fontsize=10)
# Add labels above each bar
for x, y in zip(salary_counts.index, salary_counts.values):
    plt.text(x, y + 0.5, str(y), ha='center', fontsize=10)
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Adjust layout to prevent overlap
plt.tight_layout()

# 尝试显示图表，如果失败则保存为图片
try:
    plt.show()
except Exception as e:
    print(f"显示图表时出错: {e}")
    plt.savefig('salary_chart.png')
    print("图表已保存为 salary_chart.png")

# Step 1: 预处理学历要求数据
def process_education(education):
    if '大专' in education and '以上' in education:
        return '大专及以上'
    elif '本科' in education:
        return '大专及以上'  # 本科学历也属于"大专及以上"
    else:
        return education

# 将学历要求进行归类处理
job_data['学历要求'] = job_data['学历要求'].apply(process_education)

# 统计每种学历要求的岗位数量
education_counts = job_data['学历要求'].value_counts()

# Step 2: 绘制饼状图
plt.figure(figsize=(8, 8))
plt.pie(
    education_counts.values,
    labels=education_counts.index,
    autopct='%1.1f%%',
    startangle=140,
    textprops={'fontsize': 10},
    colors=plt.cm.Paired.colors,
)
plt.title('不同学历要求的岗位数量', fontsize=16)
plt.axis('equal')  # 确保饼图为正圆形

# 尝试显示图表，如果失败则保存为图片
try:
    plt.show()
except Exception as e:
    print(f"显示图表时出错: {e}")
    plt.savefig('education_chart.png')
    print("图表已保存为 education_chart.png")